let userDao = require('../dao/userDao');
let tokenUtil = require('../token');
let timeUtil = require('../util/timeUtil');
let cmService = require('./cmService');
let apollo = require('../config/apollo');
let bcryptUtil = require('../util/bcryptUtil');
let redis = require('../dao/redis');
let redisConst = require('../const/redisConst');

const {BusiError, SysError} = require('../exception/exception');

class AuthService {
    constructor() {
    }

    /**
     * 获取授权码
     * @param {String} uid 
     */
    async getAuthCode(uid) {
        let code = new Date().getTime() + ":" + uid;
        let finalCode = bcryptUtil.hash(code);
        
        let cacheKey = redisConst.AUTH_CODE_KEY + ":" + uid;
        let res = await redis.set(cacheKey, finalCode, 1 * 60); // 有效时间1分钟
        if(res !== 'OK'){
            throw new BusiError(500, "获取authCode异常, 请稍后再试!");
        }

        console.logw("创建auth code成功:", uid, finalCode);
        return finalCode;
    }

    /**
     * 校验授权码
     * @param {String} uid 
     * @param {String} code 
     */
    async validAuthCode(uid, code){
        let cacheKey = redisConst.AUTH_CODE_KEY + ":" + uid;
        let res = await redis.get(cacheKey);
        if(!res){
            console.logw("auth code失效:", code);
            throw new BusiError(500, "auth code err");
        }

        if(res !== code) {
            console.logw("auth code校验失败, uid与auth code不匹配:", uid, code);
            throw new BusiError(500, "auth code err");
        }

        await redis.del(cacheKey);
    }
}


let authService = new AuthService();
module.exports = authService;